﻿using System;
using System.IO;
using System.Text;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc.Filters;

namespace ZilLion.Service.Core.Infrastructure.Filters
{
    public class BodyDeCodeBase64Filter : Attribute, IAsyncActionFilter
    {

        public Task OnActionExecutionAsync(ActionExecutingContext context, ActionExecutionDelegate next)
        {
            return Task.Run(
                () =>
                {
                    var stream = context.HttpContext.Request.Body;
                    context.HttpContext.Request.ContentType = "application/json";
                    var reader = new StreamReader(stream);
                    var contentstring = reader.ReadToEnd();
                    if (!contentstring.IsNotNullOrEmpty()) return;
                    var byteArray = Encoding.UTF8.GetBytes(contentstring.DecodeBase64());
                    context.HttpContext.Request.Body = new MemoryStream(byteArray);
                });
        }
    }
}